function [clickedRect, test] = clickMouseOnTargets(window, targets, clickType, whichButtons);
% checks for mouse click in rects specified in targets (one rect per row), which may be a single rect
% clickType is an optional parameter specifying whether we test for click (clickType=1) or release (clickType=0) 
% whichButtons is an optional [1-by-4] parameter specifying the mouse buttons(s) to check
% returns which rect was clicked (order of rows), 0 if none
%
% input: 
%    window: a ptb windowPtr
%    targets: an n-by-4 array, containing target rects (or a single rect if n=1)
%    [clickType]: switch, do we test for click (default, clickType ~= 0) or release (clickType == 0) of mouse button?
%    [whichButtons]: 1-by-4 vector containing list of buttons to check, default is [1 0 0 0] 
%        (NB: I have only tested this with a 4-button MightyMouse, might have to be adjusted for other mice)
% author:
%    jochen laubrock

persistent x y buttons;

assert(size(targets,2)==4);
switch nargin
    case 2, 
        clickType = 1; 
        whichButtons=[1 0 0 0]; %  default: check for left button click
    case 3, 
        whichButtons=[1 0 0 0]; %  default: check for left button click
    case 4,
        assert(unique(size(whichButtons)==[1 4])==1);
    otherwise, error('clickMouseOnTargets needs two or three arguments, but was called with %d', nargin);
end

[x,y,buttons] = GetMouse(window); % get mouse position and clicks

clickedRect = -1;
check=[0 0 0 0];
for i = 1:size(targets,1)
    check = targets(i,:);
    if x >= check(RectLeft) && x <= check(RectRight) && y >= check(RectTop) && y <= check(RectBottom)
            clickedRect = i;
            break;
    end
end

test = 0;
if clickType == 0
    test = ~unique(buttons(logical(whichButtons)));
else
    test = unique(buttons(logical(whichButtons)));
end
